package com.czwj.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czwj.annotation.SystemControllerLog;
import com.czwj.entities.DataGridData;
import com.czwj.entities.Form;
import com.czwj.entities.OperateResult;
import com.czwj.entities.PageBean;
import com.czwj.entities.PlanDaily;
import com.czwj.entities.ProjectItem;
import com.czwj.entities.UserInfo;
import com.czwj.service.FormService;
import com.czwj.service.PlanDailyService;
import com.czwj.service.ProjectItemService;
import com.czwj.util.TextUtil;
import com.czwj.util.WechatUtil;

import net.sf.json.JSONObject;

@Controller
public class PlanDailyAction {
	@Resource
	PlanDailyService planDailyService;
	
	@Resource
	ProjectItemService projectItemService;
	@Resource
	FormService formService;
	
	@Value("${review_model_code}")
	private String model_code;
	
	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@RequestMapping(value = "/plandaily", method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanDaily> planDaily(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			@RequestParam(value = "startdate", required = false) String startdate,
			@RequestParam(value = "enddate", required = false) String enddate,
			@RequestParam(value = "planmainid", required = true) Integer planmainid) {
		DataGridData<PlanDaily> result = new DataGridData();
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		if (TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)) {
			pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		}
		if (pageBean != null) {
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		if(TextUtil.isNotEmpty(startdate)){
			map.put("startdate", startdate);
		}
		if(TextUtil.isNotEmpty(enddate)){
			map.put("enddate", enddate);
		}
		map.put("planmainid", planmainid);
		List<PlanDaily> list = planDailyService.search(map);
		result.setRows(list);
		result.setTotal(planDailyService.count(map));
		return result;
	}

	@RequestMapping(value = "/planDailylist", method = RequestMethod.POST)
	@ResponseBody
	public List<PlanDaily> planDailylist() {
		List<PlanDaily> list = planDailyService.search(null);
		return list;
	}

	@SystemControllerLog(description = "修改日计划")
	@RequestMapping(value = "/planDailySave.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult planDailySave(@RequestBody PlanDaily planDaily, HttpServletRequest request)
			throws Exception {
		OperateResult result = new OperateResult();
		int count = 0;
		if (planDaily.getId() != null && planDaily.getId() > 0) {
			count = planDailyService.update(planDaily);
		} else {
			Subject currentUser = SecurityUtils.getSubject();
			planDaily.setCreaterid(((UserInfo) currentUser.getSession().getAttribute("userInfo")).getId());
			planDaily.setCreatedate(new Date());
			planDaily.setCreateip(request.getRemoteAddr());
			planDaily.setStatus(6);
			count = planDailyService.insert(planDaily);
		}
		planDaily = planDailyService.selectByPrimaryKey(planDaily.getId());
		ProjectItem projectItem = projectItemService.selectByPrimaryKey(planDaily.getPlanMain().getProjectitemid());
		for (UserInfo user : projectItem.getLevel2()) {
			JSONObject data = WechatUtil.setReviewData(projectItem.getName()+" 日计划", sdf2.format(new Date()));
			sendReview(user, data);
		}
		result.setSuccess(count > 0);
		return result;
	}

	@SystemControllerLog(description = "禁用日计划")
	@RequestMapping(value = "planDailyDelete.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult deletePlanDaily(@RequestParam("planDailyid") int id) {
		OperateResult result = new OperateResult();
		try {
			int count = planDailyService.updateStatus(id);
			result.setSuccess(count > 0);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			return result;
		}
	}
	
	@SystemControllerLog(description = "删除日计划")
	@RequestMapping(value = "planDailyRemove.do", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult removePlanDaily(@RequestParam("id") int id) {
		OperateResult result = new OperateResult();
		try {
			int count = planDailyService.remove(id);
			result.setSuccess(count > 0);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setSuccess(false);
			return result;
		}
	}
	
	@RequestMapping(value = "check/plandate", method = RequestMethod.POST)
	@ResponseBody
	public OperateResult checkPlandate(@RequestParam("mainid") int id,
			@RequestParam("plandate") String plandate,
			@RequestParam("planid") int planid){
		OperateResult result = new OperateResult();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mainid", id);
		map.put("plandate", plandate);
		PlanDaily plan = planDailyService.findbydateandmain(map);
		result.setSuccess(plan==null||plan.getId()==planid);
		return result;
	}
//	@RequestMapping(value = "plandaily/remainpercent", method = RequestMethod.GET)
//	@ResponseBody
//	public String checkRemainpercent(@RequestParam("mainid") int id,
//			@RequestParam("planid") int planid){
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("mainid", id);
//		map.put("planid", planid);
//		String percent = planDailyService.remainpercent(map);
//		return percent;
//	}
	
	
	@RequestMapping(value = "/plandaily/findoneday", method = RequestMethod.GET)
	@ResponseBody
	public List<PlanDaily> findoneday(@RequestParam("projectitemid") int projectitemid,
			@RequestParam("plandate") Date plandate){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("projectitemid", projectitemid);
		map.put("plandate", sdf.format(plandate));
		List<PlanDaily> list = planDailyService.findoneday(map);
		return list;
	}
	
	@RequestMapping(value = "/review/plandaily.do", method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanDaily> unreviewedPlanDaily(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			@RequestParam(value = "projectitemid", required = false) String projectitemid) {
		DataGridData<PlanDaily> result = new DataGridData();
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		if (TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)) {
			pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		}
		if (pageBean != null) {
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid", userInfo.getId());
		if(TextUtil.isNotEmpty(projectitemid)&&!projectitemid.equals("0")){
			map.put("projectitemid", projectitemid);
		}
		map.put("status", 6);
		result.setRows(planDailyService.searchbylevel2(map));
		result.setTotal(planDailyService.countbylevel2(map));
		return result;
	}
	
	@RequestMapping(value = "/reviewed/plandaily.do", method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanDaily> reviewedPlanDaily(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			@RequestParam(value = "startdate", required = false) String startdate,
			@RequestParam(value = "enddate", required = false) String enddate,
			@RequestParam(value = "projectitemid", required = false) String projectitemid) {
		DataGridData<PlanDaily> result = new DataGridData();
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		if (TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)) {
			pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		}
		if (pageBean != null) {
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid", userInfo.getId());
		if(TextUtil.isNotEmpty(startdate)){
			map.put("startdate", startdate);
		}
		if(TextUtil.isNotEmpty(enddate)){
			map.put("enddate", enddate);
		}
		if(TextUtil.isNotEmpty(projectitemid)&&!projectitemid.equals("0")){
			map.put("projectitemid", projectitemid);
		}
		map.put("status", "4");
		result.setRows(planDailyService.searchbylevel2(map));
		result.setTotal(planDailyService.countbylevel2(map));
		return result;
	}
	
	@RequestMapping(value = "/planDailyReviewed.do", method = RequestMethod.GET)
	@ResponseBody
	public DataGridData<PlanDaily> planDailyReviewed(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows) {
		DataGridData<PlanDaily> result = new DataGridData();
		Map<String, Object> map = new HashMap<String, Object>();
		PageBean pageBean = null;
		if (TextUtil.isNotEmpty(page) && TextUtil.isNotEmpty(rows)) {
			pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		}
		if (pageBean != null) {
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo userInfo = (UserInfo)currentUser.getSession().getAttribute("userInfo");
		map.put("userid", userInfo.getId());
		if (userInfo.getRoleid()==1||userInfo.getRoleid()==2) {

		}else if (userInfo.getRoleid()==3) {
			map.put("status", "3,4");
			result.setRows(planDailyService.searchReviewedLevel2(map));
			result.setTotal(planDailyService.countReviewedLevel2(map));
		}
		return result;
	}
	
	private void sendReview(UserInfo userInfo,JSONObject data){
		List<Form> forms = formService.findbyuser(userInfo.getId());
		for (Form form : forms) {
			String code = WechatUtil.pushMessage(userInfo.getOpenid(), model_code, form.getFormid(),data);
			formService.deleteByPrimaryKey(form.getId());
			if(code.trim().equals("0")){
				return;
			}
		}
	}
}
